package com.yixuan.mt.common.service.impl_mysql;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.yixuan.mt.common.entity.Policy;
import com.yixuan.mt.common.exception.HttpBadRequestException;
import com.yixuan.mt.common.mapper.PoliciesMapper;
import com.yixuan.mt.common.request.PostPoliciesRequest;
import com.yixuan.mt.common.service.PoliciesService;
import com.yixuan.mt.common.utitls.PoliciesCacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PoliciesServiceMysqlImpl implements PoliciesService {

    @Autowired
    private PoliciesMapper policiesMapper;

    @Autowired
    private PoliciesCacheUtils policiesCacheUtils;

    @Override
    public void postPolicies(PostPoliciesRequest postPoliciesRequest) {
        // 唯一性判断
        if (policiesMapper.selectIsExistByName(postPoliciesRequest.getName())) {
            throw new HttpBadRequestException("策略名重复！");
        }

        policiesMapper.insertPolicy(postPoliciesRequest);
    }

    @Override
    public void deletePolicies(Integer id) throws JsonProcessingException {
        policiesMapper.deletePolicy(id);
        policiesCacheUtils.updatePolicyCache(id);
    }

    @Override
    public void putPolicies(Policy policy) throws JsonProcessingException {
        policiesMapper.updatePolicy(policy);
        policiesCacheUtils.updatePolicyCache(policy.getId());
    }

    @Override
    public List<Policy> getPoliciesList() {
        return policiesMapper.selectPoliciesList();
    }

    @Override
    public List<Policy> getPoliciesList(Integer[] ids) {
        return policiesMapper.selectPoliciesListByIds(ids);
    }

    @Override
    public String getPolicyDetail(Integer id) {
        return policiesMapper.selectPolicyDetail(id);
    }
}
